// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.api;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.util.StringUtils;
import com.liuxinlong.common.AosException;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.entity.FileManage;
import com.liuxinlong.modules.entity.SharePointHeader;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.mapper.SharePointHeaderMapper;
import com.liuxinlong.utils.EncryptUtils;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.UrlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SPO服务器api
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2022年2月25日
 */
@Service
@Slf4j
public class SPORequestService implements SPOInterface {
    @Autowired
    private SharePoint sharePoint;

    @Autowired
    private SharePointHeaderMapper sharePointHeaderMapper;

    public final static String SEARCH_FILE_GET_URL = "/_api/search/query";

    public final static String DOWNLOAD_FILE_DIR = "downloadSpo/";

    /**
     * 连接spo服务器，获取请求字段
     *
     * @param user 用户信息
     * @return SPORequestHeaderDto
     */
    public SPORequestHeaderDto connectSPO(User user) {
        SPORequestHeaderDto spoRequestHeaderDto = new SPORequestHeaderDto();
        String securityToken = getSecurityToken(sharePoint.getUsername(), sharePoint.getPassword());
        if (StringUtils.isEmpty(securityToken)) {
            throw new AosException(ReturnCodes.HTTP_ACCESS_FAIL_SECURITY_TOKEN);
        }
        List<String> accessToken = getAccessToken(securityToken);
        if (ObjectUtils.isEmpty(accessToken)) {
            throw new AosException(ReturnCodes.HTTP_ACCESS_FAIL_ACCESS_TOKEN);
        }
        String fedAuth = "";
        String rtFa = "";
        for (String cookie : accessToken) {
            if (cookie.length() > 8 && StringUtils.equals(cookie.substring(0, 8), "FedAuth=")) {
                fedAuth = cookie;
                continue;
            }
            if (cookie.length() > 5 && StringUtils.equals(cookie.substring(0, 5), "rtFa=")) {
                rtFa = cookie;
            }
        }
        String requestDigest = getRequestDigest(fedAuth + ";" + rtFa);
        if (StringUtils.isEmpty(requestDigest)) {
            throw new AosException(ReturnCodes.HTTP_ACCESS_FAIL_REQUEST_DIGEST);
        }

        spoRequestHeaderDto.setSecurityToken(securityToken);
        spoRequestHeaderDto.setFedAuth(fedAuth);
        spoRequestHeaderDto.setRtFa(rtFa);
        spoRequestHeaderDto.setRequestDigest(requestDigest);
        sharePointHeaderMapper.deleteById("1");
        SharePointHeader sharePointHeader = new SharePointHeader();
        sharePointHeader.setId("1");
        sharePointHeader.setSecurityToken(securityToken);
        sharePointHeader.setFedAuth(fedAuth);
        sharePointHeader.setRtFa(rtFa);
        sharePointHeader.setRequestDigest(requestDigest);
        sharePointHeaderMapper.insert(sharePointHeader);
        return spoRequestHeaderDto;
    }

    /**
     * 获取 SecurityToken
     *
     * @param username 用户名
     * @param password 密码
     * @return SecurityToken
     */
    private String getSecurityToken(String username, String password) {
        StringBuffer buffer = new StringBuffer();
        String securityToken = null;
        try {
            URL url = new URL(sharePoint.getLogin());
            //http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestMethod("POST");

            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);
            httpUrlConn.connect();

            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            StringBuffer pstr = new StringBuffer();
            InputStream fileIs = this.getClass().getResourceAsStream("/spoToken.xml");

            int length = 0;
            //通过循环来判断是否读取到文件的末尾
            while ((length = fileIs.read()) != -1) {
                //输出读取到的字符
                pstr.append((char) length);
            }
            osw.write(String.valueOf(pstr).replace("targetUser", username).replace("targetPass", password).replace("targetAddress", sharePoint.getMainsite()));
            osw.flush();

            fileIs.close();
            osw.close();

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            log.info(buffer.toString());
            securityToken = getXMLvalue(buffer.toString(), "wsse:BinarySecurityToken");
            log.info("getXMLvalue success");
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "获取 SecurityToken失败");
        }
        return securityToken;
    }

    /**
     * 获取 AccessToken
     *
     * @param securityToken securityToken
     * @return AccessToken
     */
    private List<String> getAccessToken(String securityToken) {
        StringBuffer buffer = new StringBuffer();
        List<String> accessToken = null;
        try {
            URL url = new URL(sharePoint.getMainsite() + sharePoint.getSession());
            //http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestMethod("POST");
            buildFoundation(httpUrlConn);

            httpUrlConn.setUseCaches(false);
            //必须设置false，否则会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(false);

            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write(securityToken);
            osw.flush();
            osw.close();

            httpUrlConn.connect();
            Map<String, List<String>> map = httpUrlConn.getHeaderFields();

            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();
            accessToken = map.get("Set-Cookie");

//            httpUrlConn.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "获取 AccessToken失败");
        } finally {

        }
        return accessToken;
    }

    /**
     * 获取 RequestDigest
     *
     * @param cookie cookie
     * @return RequestDigest
     */
    private String getRequestDigest(String cookie) {
        String requestDigest = null;
        HttpURLConnection httpUrlConn = null;
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(sharePoint.getMainsite() + sharePoint.getDigest());
            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);

            httpUrlConn.setRequestMethod("POST");
//            buildFoundation(httpUrlConn);
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
            httpUrlConn.setRequestProperty("Cookie", cookie);

            httpUrlConn.setUseCaches(false);
            //必须设置true，否则不会自动redirect到重定向后的地址
            httpUrlConn.setInstanceFollowRedirects(true);

            httpUrlConn.connect();

            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            osw.write("");
            osw.flush();
            osw.close();
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            //释放资源
            inputStream.close();
            httpUrlConn.disconnect();

            requestDigest = getXMLvalue(buffer.toString(), "d:FormDigestValue");
//            log.info("resp: ", buffer.toString());
//
//            log.info("requestDigest:  ", requestDigest);
//            System.out.println("resp: " + buffer.toString());
//            System.out.println("requestDigest: " + requestDigest);
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "获取 RequestDigest失败");
        } finally {
            if (httpUrlConn != null) {
                httpUrlConn.disconnect();
            }

        }
        return requestDigest;
    }

    /**
     * 文件下载
     *
     * @param spo       连接参数
     * @param targetDir 目标文件夹
     * @param fileName  文件名称
     * @return 文件暂存路径
     */
    public String downloadFile(SPORequestHeaderDto spo, String targetDir, String fileName) {
        log.info("targetDir: ", targetDir);
        String targetUrl;
        if (targetDir.contains(":")) {
            targetUrl = UrlUtils.encodeURLChinese(targetDir);
        } else {
            String targetPath = targetDir + "/" + fileName;
            String fullUrl = StringUtils.isEmpty(sharePoint.getSubsite()) ? sharePoint.getMainsite() : sharePoint.getMainsite() + sharePoint.getSubsite();
            targetUrl = UrlUtils.encodeURLChinese(fullUrl + sharePoint.getDownload().replace("targetPath", targetPath));
        }
        log.info("targetUrl: ", targetUrl);
        HttpURLConnection httpUrlConn = null;
        try {

            URL url = new URL(targetUrl);

            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            buildFoundation(httpUrlConn);
            httpUrlConn.setRequestProperty("Cookie", spo.getFedAuth() + ";" + spo.getRtFa());
            httpUrlConn.setRequestProperty("X-RequestDigest", spo.getRequestDigest());
            httpUrlConn.setRequestProperty("Authorization", "Bearer " + spo.getRequestDigest());

            log.info("targetUrl11: " + targetUrl);
            log.info("FedAuth: " + spo.getFedAuth());
            log.info("RtFa: " + spo.getRtFa());
            log.info("X-RequestDigest: " + spo.getRequestDigest());
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.connect();

            int code = httpUrlConn.getResponseCode();
            if (code == 403 || code == 401) {
                //释放资源
                httpUrlConn.disconnect();
                if (spo.isRedo()) {
                    throw new AosException(ReturnCodes.HTTP_ACCESS_FAIL_CONNECT);
                }
                User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//                user.setEmail(sharePoint.getUsername());
                user.setPassword(EncryptUtils.AESEncode(sharePoint.getPassword()));
                SPORequestHeaderDto newSpo = connectSPO(user);
                newSpo.setRedo(true);
                downloadFile(newSpo, targetDir, fileName);
            } else {
                log.info("start download file");
                // 目标路径
                File localFile = new File(DOWNLOAD_FILE_DIR);
                // 如果文件目录不存在，就执行创建
                if (!localFile.isDirectory()) {
                    localFile.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(DOWNLOAD_FILE_DIR + fileName);
                BufferedOutputStream bos = new BufferedOutputStream(fos);

                //将返回的输入流转换成文件
                InputStream in = httpUrlConn.getInputStream();
                byte[] buffer = new byte[4096];
                int len = 0;
                while ((len = in.read(buffer, 0, buffer.length)) != -1) {
                    bos.write(buffer, 0, len);
                }

                bos.flush();
                bos.close();
                log.info("文件下载成功");
                log.info("==========================");
                //释放资源
                in.close();
            }

            httpUrlConn.disconnect();
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "文件下载失败");
        } finally {
            httpUrlConn.disconnect();
        }
        return DOWNLOAD_FILE_DIR + fileName;
    }

    /**
     * 文件上传
     *
     * @param spo              连接参数
     * @param targetDir        目标文件夹
     * @param localInputStream 本地文件流
     * @param fileName         文件名称
     * @return 文件管理信息
     */
    public FileManage uploadFileStream(SPORequestHeaderDto spo, String targetDir, InputStream localInputStream, String fileName) {
        String fullUrl = StringUtils.isEmpty(sharePoint.getSubsite()) ? sharePoint.getMainsite() : sharePoint.getMainsite() + sharePoint.getSubsite();
        String targetUrl = UrlUtils.encodeURLChinese(fullUrl + sharePoint.getUpload().replace("targetDocuments", targetDir).replace("targetFile", fileName));
        StringBuffer buffer = new StringBuffer();
        FileManage fileInfo = new FileManage();
        HttpURLConnection httpUrlConn = null;
        try {
            URL url = new URL(targetUrl);

            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setRequestMethod("POST");
            buildFoundation(httpUrlConn);
            httpUrlConn.setRequestProperty("Cookie", spo.getFedAuth() + ";" + spo.getRtFa());
            httpUrlConn.setRequestProperty("X-RequestDigest", spo.getRequestDigest());
            httpUrlConn.setRequestProperty("Authorization", "Bearer " + spo.getRequestDigest());

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.connect();

            OutputStream os = httpUrlConn.getOutputStream();
            byte[] upBuffer = new byte[4096];
            int len = 0;
            while ((len = localInputStream.read(upBuffer, 0, upBuffer.length)) != -1) {
                os.write(upBuffer, 0, len);
            }
            os.flush();
            os.close();

            int code = httpUrlConn.getResponseCode();

            if (code == 403 || code == 401) {
                //释放资源
                httpUrlConn.disconnect();
                if (spo.isRedo()) {
                    throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "用户无操作权限");
                }
                User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//                user.setEmail(sharePoint.getUsername());
                user.setPassword(EncryptUtils.AESEncode(sharePoint.getPassword()));
                SPORequestHeaderDto newSpo = connectSPO(user);
                newSpo.setRedo(true);
                fileInfo = uploadFileStream(newSpo, targetDir, localInputStream, fileName);
            } else {
                InputStream inputStream = httpUrlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                //释放资源
                inputStream.close();
                httpUrlConn.disconnect();

                JSONObject res = JSONUtil.parseObj(buffer);
                JSONObject resB = res.getJSONObject("d");
                Map<String, Object> resMap = JSONUtil.parseObj(resB);
                String previewPath = (String) resMap.get("LinkingUrl");
                fileInfo.setPreviewPath(previewPath);
                String originalUrl = sharePoint.getMainsite() + targetDir + File.separator + fileName;
                fileInfo.setFilePath(originalUrl);

                log.info("文件上传成功");
                log.info("==========================");
            }
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } finally {
            httpUrlConn.disconnect();
        }
        return fileInfo;
    }

    /**
     * 文件上传
     *
     * @param spo       连接参数
     * @param targetDir 目标文件夹
     * @param localPath 本地路径
     * @param fileName  文件名称
     * @return 文件管理信息
     */
    public FileManage uploadFile(SPORequestHeaderDto spo, String targetDir, String localPath, String fileName) {
        String fullUrl = StringUtils.isEmpty(sharePoint.getSubsite()) ? sharePoint.getMainsite() : sharePoint.getMainsite() + sharePoint.getSubsite();
        String targetUrl = UrlUtils.encodeURLChinese(fullUrl + sharePoint.getUpload().replace("targetDocuments", targetDir).replace("targetFile", fileName));
        StringBuffer buffer = new StringBuffer();
        FileManage fileInfo = new FileManage();
        HttpURLConnection httpUrlConn = null;
        try {
            URL url = new URL(targetUrl);

            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);
            httpUrlConn.setRequestMethod("POST");
            buildFoundation(httpUrlConn);
            httpUrlConn.setRequestProperty("Cookie", spo.getFedAuth() + ";" + spo.getRtFa());
            httpUrlConn.setRequestProperty("X-RequestDigest", spo.getRequestDigest());
            httpUrlConn.setRequestProperty("Authorization", "Bearer " + spo.getRequestDigest());

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.connect();

            FileInputStream fis = new FileInputStream(localPath);
            OutputStream os = httpUrlConn.getOutputStream();
            byte[] upBuffer = new byte[4096];
            int len = 0;
            while ((len = fis.read(upBuffer, 0, upBuffer.length)) != -1) {
                os.write(upBuffer, 0, len);
            }
            os.flush();
            os.close();

            int code = httpUrlConn.getResponseCode();

            if (code == 403 || code == 401) {
                //释放资源
                httpUrlConn.disconnect();
                if (spo.isRedo()) {
                    throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "用户无操作权限");
                }
                User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//                user.setEmail(sharePoint.getUsername());
                user.setPassword(EncryptUtils.AESEncode(sharePoint.getPassword()));
                SPORequestHeaderDto newSpo = connectSPO(user);
                newSpo.setRedo(true);
                fileInfo = uploadFile(newSpo, targetDir, localPath, fileName);
            } else {
                InputStream inputStream = httpUrlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                //释放资源
                inputStream.close();
                httpUrlConn.disconnect();

                JSONObject res = JSONUtil.parseObj(buffer);
                JSONObject resB = res.getJSONObject("d");
                Map<String, Object> resMap = JSONUtil.parseObj(resB);
                String previewPath = (String) resMap.get("LinkingUrl");
                fileInfo.setPreviewPath(previewPath);
                String originalUrl = sharePoint.getMainsite() + targetDir + File.separator + fileName;
                fileInfo.setFilePath(originalUrl);

                log.info("文件上传成功");
                log.info("==========================");
            }
        } catch (ConnectException e) {
            e.printStackTrace();
            log.error("ConnectException");
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            log.error("AosException");
            throw e;
        } catch (Exception e) {
            log.error("Exception : " + e.toString());
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } finally {
            httpUrlConn.disconnect();
        }
        return fileInfo;
    }

    /**
     * 获取某一文件夹下全部文件列表
     *
     * @param spo 连接参数
     * @param dir 文件夹路径
     */
    public List<FileManage> getDirFileList(SPORequestHeaderDto spo, String dir) {
        String fullUrl = StringUtils.isEmpty(sharePoint.getSubsite()) ? sharePoint.getMainsite() : sharePoint.getMainsite() + sharePoint.getSubsite();
        String targetUrl = UrlUtils.encodeURLChinese(fullUrl + "/_api/web/GetFolderByServerRelativeUrl('"+dir+"')/Files");
        StringBuffer buffer = new StringBuffer();
        List<FileManage> fileList = new ArrayList<>();
        try {
            URL url = new URL(targetUrl);

            //http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            buildFoundation(httpUrlConn);
            httpUrlConn.setRequestProperty("Cookie", spo.getFedAuth() + ";" + spo.getRtFa());
            httpUrlConn.setRequestProperty("X-RequestDigest", spo.getRequestDigest());
            httpUrlConn.setRequestProperty("Authorization", "Bearer " + spo.getRequestDigest());
            httpUrlConn.setRequestMethod("GET");

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.connect();

            int code = httpUrlConn.getResponseCode();
            if (code == 403 || code == 401) {
                //释放资源
                httpUrlConn.disconnect();
                if (spo.isRedo()) {
                    throw new AosException(ReturnCodes.HTTP_ACCESS_FAIL_CONNECT);
                }
                User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//                user.setEmail(sharePoint.getUsername());
                user.setPassword(sharePoint.getPassword());
                SPORequestHeaderDto newSpo = connectSPO(user);
                newSpo.setRedo(true);
                fileList = getDirFileList(newSpo, dir);
            } else {
                InputStream inputStream = httpUrlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                //释放资源
                inputStream.close();
                httpUrlConn.disconnect();

//                log.info("files: " + buffer.toString());
                JSONObject res = JSONUtil.parseObj(buffer);
                JSONObject resB = res.getJSONObject("d");
                Map<String, Object> resMap = JSONUtil.parseObj(resB);
                JSONArray results = (JSONArray) resMap.get("results");
                if (ObjectUtils.isEmpty(results)) {
                    return fileList;
                }
                for (Object result : results) {
                    Map<String, Object> item = new HashMap<>();
                    if (ObjectUtils.isEmpty(res)) {
                        continue;
                    }
                    JSONObject resI = JSONUtil.parseObj(result);
                    log.info("file: " + resI.toString());
                }
            }
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } finally {

        }
        return fileList;
    }

    /**
     * 获取xml文本中tag值
     *
     * @param xml     xml文本
     * @param tagName tag名称
     * @return tag值
     */
    private String getXMLvalue(String xml, String tagName) {
        String value = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            Document document = db.parse(new ByteArrayInputStream(xml.getBytes()));

            NodeList node = document.getElementsByTagName(tagName);
//            Element element = (Element) node.item(0);

            value = node.item(0).getFirstChild().getNodeValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 文件检索
     *
     * @param spo 连接参数
     * @return 查询结果
     */
    public Map<String, Object> searchFilePost(SPORequestHeaderDto spo, String keyword, int startNum, int pageSize) {
        String siteUrl = StringUtils.isEmpty(sharePoint.getSubsite()) ? sharePoint.getMainsite(): sharePoint.getMainsite() + sharePoint.getSubsite();
        String filePath = "http://aosmithcorporationapc.sharepoint.com/sites/DKSTest_01/Shared Documents";
        String oriUrl =  siteUrl + sharePoint.getSearch();
//        String oriUrl =  filePath + sharePoint.getSearch();
        String targetUrl = UrlUtils.encodeURLChinese(oriUrl);
        StringBuffer buffer = new StringBuffer();
        Map<String, Object> resultMap = new HashMap<>();
        HttpURLConnection httpUrlConn = null;
        try {
            URL url = new URL(targetUrl);

            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);

            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            // Content-Type要配置为application/json 否则报错400
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
            httpUrlConn.setRequestProperty("Cookie", spo.getFedAuth() + ";" + spo.getRtFa());
//            httpUrlConn.setRequestProperty("X-RequestDigest", spo.getRequestDigest());
            httpUrlConn.setRequestProperty("Authorization", "Bearer " + spo.getRequestDigest());
            httpUrlConn.setRequestMethod("POST");

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            Map<String, Map<String, Object>> queryMap = new HashMap<>();
            Map<String, Object> param = new HashMap<>();
            List<String> queryProperties = new ArrayList<>();
            queryProperties.add("Title");
            queryProperties.add("ID");
            queryProperties.add("SiteId");
            queryProperties.add("HitHighlightedSummary");
            queryProperties.add("editorowsuser");
            queryProperties.add("authorowsuser");
            queryProperties.add("Filename");
            queryProperties.add("SPSiteURL");
            queryProperties.add("ParentLink");
            queryProperties.add("ListItemID");
            queryProperties.add("ListID");
            queryProperties.add("contentclass");
            queryProperties.add("IsDocument");
            queryProperties.add("IsContainer");
            queryProperties.add("FileExtension");
//            queryProperties.add("SecondaryFileExtension");
            queryProperties.add("OriginalPath");
            queryProperties.add("DefaultEncodingURL");
            queryProperties.add("ServerRedirectedURL");
            queryProperties.add("ServerRedirectedPreviewURL");
//            queryProperties.add("LastModifiedTime");
//            queryProperties.add("SharedWithUsersOWSUser");
//            queryProperties.add("ModifierDates");
//            queryProperties.add("LastModifiedTimeForRetention");

            queryProperties.add("PictureThumbnailURL");
            queryProperties.add("ServerRedirectedEmbedURL");
            queryProperties.add("Path");

            List<String> reProperties = new ArrayList<>();
            reProperties.add("Title");
//            reProperties.add("SiteId");
//            reProperties.add("HitHighlightedSummary");
//            param.put("Querytext", keyword+ " AND WebId:"+ sharePoint.getWebid() + " AND filetype:(\"docx\" OR \"xlsx\") ");
            param.put("Querytext", keyword +"* AND WebId:" + sharePoint.getWebid());
            List<Map<String,Object>> sortList = new ArrayList<>();
            Map<String,Object> sortParam1 = new HashMap<>();
            sortParam1.put("Property","Rank");
//            sortParam1.put("Property","Created");
            sortParam1.put("Direction","0");
            sortList.add(sortParam1);
            param.put("SortList", sortList);
            param.put("StartRow", startNum);
            param.put("RowLimit", pageSize);
            param.put("SummaryLength", 200);
            param.put("SelectProperties", queryProperties);
            param.put("HitHighlightedProperties", reProperties);
            param.put("TrimDuplicates", false);
            param.put("Refiners", "companies,contentclass,FileType(filter=6/0/*)");
            List<String> refinersFilter = new ArrayList<>();
            refinersFilter.add("IsDocument:equals(true)");
            refinersFilter.add("or(FileExtension:equals(\"docx\"),FileExtension:equals(\"xlsx\"),FileExtension:equals(\"pdf\"))");
            param.put("RefinementFilters", refinersFilter);
            queryMap.put("request", param);
            log.info("request:", com.alibaba.fastjson.JSONObject.toJSONString(param));
            System.out.println( com.alibaba.fastjson.JSONObject.toJSONString(param));
            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");

            osw.write(JSONUtil.toJsonStr(queryMap));
            osw.flush();
            osw.close();

            httpUrlConn.connect();

            int code = httpUrlConn.getResponseCode();
            log.info("code: " + code);
            log.info("httpUrlConn: " + httpUrlConn.getResponseMessage());
            if (code == 403 || code == 401) {
                //释放资源
                httpUrlConn.disconnect();
                if (spo.isRedo()) {
                    throw new AosException(ReturnCodes.HTTP_ACCESS_FAIL_CONNECT);
                }
                User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//                user.setEmail(sharePoint.getUsername());
                user.setPassword(sharePoint.getPassword());
                SPORequestHeaderDto newSpo = connectSPO(user);
                newSpo.setRedo(true);
                resultMap = searchFilePost(newSpo, keyword, startNum, pageSize);
            } else {
                InputStream inputStream = httpUrlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                //释放资源
                inputStream.close();
                httpUrlConn.disconnect();

//                log.info("resp: " + buffer);
                JSONObject res = JSONUtil.parseObj(buffer);
                resultMap = spliceQueryData(res);
                log.info("文件查询成功");

                log.info("==========================");
            }
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            log.error(e.toString());
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "连接SPO查询文件信息失败");
        } finally {
            httpUrlConn.disconnect();
        }
        return resultMap;
    }

    /**
     * 文件检索
     *
     * @param spo 连接参数
     */
    public void searchFileGet(SPORequestHeaderDto spo, String keyword) {
//        String oriUrl = sharePoint.getSite() + SEARCH_FILE_GET_URL + "?querytext='"+keyword + "'&rowLimit=10";
        String fullUrl = StringUtils.isEmpty(sharePoint.getSubsite()) ? sharePoint.getMainsite() : sharePoint.getMainsite() + sharePoint.getSubsite();
        String oriUrl = UrlUtils.encodeURLChinese(fullUrl + SEARCH_FILE_GET_URL + "?querytext='" + keyword + "'");
        String targetUrl = UrlUtils.encodeURLChinese(oriUrl);
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(targetUrl);

            //http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            buildFoundation(httpUrlConn);
            httpUrlConn.setRequestProperty("Cookie", spo.getFedAuth() + ";" + spo.getRtFa());
            httpUrlConn.setRequestProperty("X-RequestDigest", spo.getRequestDigest());

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            log.info("url: " + targetUrl);
            log.info("RtFa: " + spo.getRtFa());
            log.info("FedAuth: " + spo.getFedAuth());
            log.info("X-RequestDigest: " + spo.getRequestDigest());

            httpUrlConn.connect();
            int code = httpUrlConn.getResponseCode();
            if (code == 403 || code == 401) {
                //释放资源
                httpUrlConn.disconnect();
                if (spo.isRedo()) {
                    throw new AosException(ReturnCodes.HTTP_ACCESS_FAIL_CONNECT);
                }
                User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//                user.setEmail(sharePoint.getUsername());
                user.setPassword(sharePoint.getPassword());
                SPORequestHeaderDto newSpo = connectSPO(user);
                newSpo.setRedo(true);
                searchFileGet(newSpo, keyword);
            } else {
                InputStream inputStream = httpUrlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                //释放资源
                inputStream.close();
                httpUrlConn.disconnect();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void moveFile(SPORequestHeaderDto spo, String originPath, String targetPath) {
        String fullUrl = StringUtils.isEmpty(sharePoint.getSubsite()) ? sharePoint.getMainsite() : sharePoint.getMainsite() + sharePoint.getSubsite();
        String ori = originPath.replace(fullUrl, sharePoint.getSubsite());
        String targetUrl = UrlUtils.encodeURLChinese(fullUrl + sharePoint.getMove().replace("targetFilePath", ori).replace("newFilePath", sharePoint.getSubsite() + targetPath));
        StringBuffer buffer = new StringBuffer();
        Map<String, Object> resultMap = new HashMap<>();
        log.info("targetUrl:  ",targetUrl);
        HttpURLConnection httpUrlConn = null;
        try {
            URL url = new URL(targetUrl);

            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);

            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            // Content-Type要配置为application/json 否则报错400
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
            httpUrlConn.setRequestProperty("Cookie", spo.getFedAuth() + ";" + spo.getRtFa());
            httpUrlConn.setRequestProperty("Authorization", "Bearer " + spo.getRequestDigest());
            httpUrlConn.setRequestMethod("POST");

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");

            osw.flush();
            osw.close();

            httpUrlConn.connect();

            int code = httpUrlConn.getResponseCode();
            log.info("code: " + code);
            if (code == 403 || code == 401) {
                //释放资源
                httpUrlConn.disconnect();
                if (spo.isRedo()) {
                    throw new AosException(ReturnCodes.HTTP_ACCESS_FAIL_CONNECT);
                }
                User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//                user.setEmail(sharePoint.getUsername());
                user.setPassword(sharePoint.getPassword());
                SPORequestHeaderDto newSpo = connectSPO(user);
                newSpo.setRedo(true);
                moveFile(newSpo, originPath, targetPath);
            } else {
                InputStream inputStream = httpUrlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                //释放资源
                inputStream.close();
                httpUrlConn.disconnect();

//                log.info("resp: " + buffer);
                log.info("文件移动成功");

                log.info("==========================");
            }
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        }  catch (FileNotFoundException e) {
            log.error(e.toString());
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "移动SPO文件失败,文件在spo不存在");
        }  catch (AosException e) {
            throw e;
        } catch (Exception e) {
            log.error(e.toString());
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "连接SPO移动文件失败");
        } finally {
            httpUrlConn.disconnect();
        }
    }

    @Override
    public void removeFile(SPORequestHeaderDto spo, String spoFilePath) {
        String fullUrl = StringUtils.isEmpty(sharePoint.getSubsite()) ? sharePoint.getMainsite() : sharePoint.getMainsite() + sharePoint.getSubsite();
        String dealFilePath = spoFilePath.replace(fullUrl, sharePoint.getSubsite());
        String targetOriginUrl = UrlUtils.encodeURLChinese(fullUrl + sharePoint.getObtain().replace("targetFilePath", dealFilePath));
        String targetUrl = UrlUtils.encodeURLChinese(targetOriginUrl);
        StringBuffer buffer = new StringBuffer();
        Map<String, Object> resultMap = new HashMap<>();
        HttpURLConnection httpUrlConn = null;
        try {
            URL url = new URL(targetUrl);

            //http协议传输
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setConnectTimeout(5000);
            httpUrlConn.setReadTimeout(5000);

            httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
            httpUrlConn.setRequestProperty("Connection", "keep-alive");
            // Content-Type要配置为application/json 否则报错400
            httpUrlConn.setRequestProperty("Content-Type", "application/json");
            httpUrlConn.setRequestProperty("Content-Length", "0");
            httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
            httpUrlConn.setRequestProperty("Cookie", spo.getFedAuth() + ";" + spo.getRtFa());
            httpUrlConn.setRequestProperty("Authorization", "Bearer " + spo.getRequestDigest());
            httpUrlConn.setRequestProperty("X-HTTP-Method", "DELETE");
            httpUrlConn.setRequestProperty("IF-MATCH", "etag or \"*\"");

            httpUrlConn.setRequestMethod("POST");

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            OutputStream os = httpUrlConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");

            osw.flush();
            osw.close();

            httpUrlConn.connect();

            int code = httpUrlConn.getResponseCode();
            log.info("code: " + code);
            if (code == 403 || code == 401) {
                //释放资源
                httpUrlConn.disconnect();
                if (spo.isRedo()) {
                    throw new AosException(ReturnCodes.HTTP_ACCESS_FAIL_CONNECT);
                }
                User user = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
//                user.setEmail(sharePoint.getUsername());
                user.setPassword(sharePoint.getPassword());
                SPORequestHeaderDto newSpo = connectSPO(user);
                newSpo.setRedo(true);
                removeFile(newSpo, spoFilePath);
            } else {
                InputStream inputStream = httpUrlConn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    buffer.append(str);
                }
                bufferedReader.close();
                inputStreamReader.close();
                //释放资源
                inputStream.close();
                httpUrlConn.disconnect();

//                log.info("resp: " + buffer);
//                JSONObject res = JSONUtil.parseObj(buffer);
                log.info("文件删除成功");

                log.info("==========================");
            }
        } catch (ConnectException e) {
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, e.getMessage());
        } catch (FileNotFoundException e) {
            log.error(e.toString());
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "删除SPO文件失败,文件在spo不存在");
        } catch (AosException e) {
            throw e;
        } catch (Exception e) {
            log.error(e.toString());
            e.printStackTrace();
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR, "删除SPO文件失败");
        } finally {
            httpUrlConn.disconnect();
        }
    }


    private Map<String, Object> spliceQueryData(JSONObject sourceResp) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        JSONObject resB = sourceResp.getJSONObject("d");
        if (ObjectUtils.isEmpty(resB)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        JSONObject resC = resB.getJSONObject("postquery");
        if (ObjectUtils.isEmpty(resC)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        JSONObject resD = resC.getJSONObject("PrimaryQueryResult");
        if (ObjectUtils.isEmpty(resD)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        JSONObject resE = resD.getJSONObject("RelevantResults");
        if (ObjectUtils.isEmpty(resE)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        int totalNum = (int) resE.get("TotalRows");
        JSONObject resF = resE.getJSONObject("Table");
        if (ObjectUtils.isEmpty(resF)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        JSONObject resG = resF.getJSONObject("Rows");
        if (ObjectUtils.isEmpty(resG)) {
            throw new AosException(ReturnCodes.HTTP_SYSTEM_ERROR);
        }
        JSONArray resH = resG.getJSONArray("results");
        if (ObjectUtils.isEmpty(resH)) {
            resultMap.put("dataList", resultList);
            resultMap.put("totalNum", 0);
            return resultMap;
        }

        int i = 1;
        String fullUrl = StringUtils.isEmpty(sharePoint.getSubsite()) ? sharePoint.getMainsite() : sharePoint.getMainsite() + sharePoint.getSubsite();
        for (Object res : resH) {
            Map<String, Object> item = new HashMap<>();
            if (ObjectUtils.isEmpty(res)) {
                continue;
            }
            JSONObject resI = JSONUtil.parseObj(res);
            JSONObject resJ = resI.getJSONObject("Cells");
            JSONArray resK = resJ.getJSONArray("results");

            for (Object resInner : resK) {
                if (ObjectUtils.isEmpty(resInner)) {
                    continue;
                }
                Map<String, Object> map = (Map<String, Object>) resInner;
                if (StringUtils.equals((String) map.get("Key"), "Title")) {
                    item.put("title", map.get("Value"));
                } else if (StringUtils.equals((String) map.get("Key"), "HitHighlightedSummary")) {
                    item.put("content", JSONUtil.isNull(map.get("Value")) ? "" : map.get("Value"));
                } else if (StringUtils.equals((String) map.get("Key"), "Rank")) {
                    item.put("rank", map.get("Value"));
                } else if (StringUtils.equals((String) map.get("Key"), "DocId")) {
                    item.put("docId", map.get("Value"));
                } else if (StringUtils.equals((String) map.get("Key"), "ID")) {
                    item.put("spoId", map.get("Value"));
                } else if (StringUtils.equals((String) map.get("Key"), "ServerRedirectedPreviewURL")) {
                    item.put("imagePreview", JSONUtil.isNull(map.get("Value")) ? "" : map.get("Value"));
                } else if (StringUtils.equals((String) map.get("Key"), "MajorVersion")) {
                    item.put("version", JSONUtil.isNull(map.get("Value")) ? "" : map.get("Value"));
                } else if (StringUtils.equals((String) map.get("Key"), "Path")) {
                    item.put("path", JSONUtil.isNull(map.get("Value")) ? "" : (String) map.get("Value"));
                }
//                else if (StringUtils.equals((String) map.get("Key"), "DefaultEncodingURL")) {
//                    item.put("previewUrl", JSONUtil.isNull(map.get("Value")) ? "" :((String) map.get("Value")).replace(fullUrl,""));
//                }
                else if (StringUtils.equals((String) map.get("Key"), "FileExtension")) {
                    item.put("fileType", JSONUtil.isNull(map.get("Value")) ? "" : map.get("Value"));
                } else if (StringUtils.equals((String) map.get("Key"), "Filename")) {
                    item.put("fileName", JSONUtil.isNull(map.get("Value")) ? "" : map.get("Value"));
                }
            }
            // 只查询在用库数据
            String path = (String) item.get("path");
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(path) && !path.contains("Shared Documents")) {
                continue;
            }
            resultList.add(item);
            i++;
        }
        resultMap.put("dataList", resultList);
        resultMap.put("totalNum", totalNum);
        return resultMap;
    }

    private HttpURLConnection buildFoundation(HttpURLConnection httpUrlConn) {
        httpUrlConn.setRequestProperty("Accept", "application/json;odata=verbose");
        httpUrlConn.setRequestProperty("Connection", "keep-alive");
        httpUrlConn.setRequestProperty("Content-Type", "application/json;odata=verbose");
        httpUrlConn.setRequestProperty("Content-Length", "0");
        httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
        return httpUrlConn;
    }
}
